package com.zzzyh.forumsystemclient.handler;

import com.alibaba.fastjson.JSON;
import com.zzzyh.forumsystemclient.common.AppResult;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
     @author 郑雨杭
     @create 2025/4/26 - 13:37
 */
 //匿名访问异常处理器
 @Component
 public class AnonymousAuthenticationHandler implements AuthenticationEntryPoint {
  @Override
  public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
    response.setContentType("application/json;charset=UTF-8");
    ServletOutputStream outputStream = response.getOutputStream();
    String jsonString = "";
    if (authException instanceof InternalAuthenticationServiceException){
        jsonString = JSON.toJSONString(AppResult.failed("用户不存在"));
    }else if(authException instanceof BadCredentialsException ){
        jsonString = JSON.toJSONString(AppResult.failed("用户名或密码错误"));
    }else {
        jsonString = JSON.toJSONString(AppResult.failed("认证失败"));
    }
   outputStream.write(jsonString.getBytes("UTF-8"));
    outputStream.flush();
    outputStream.close();
  }
}
